package org.cable.link.strategy;

import org.apache.commons.lang3.StringUtils;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.cable.common.enums.BizCodeEnum;
import org.cable.common.exception.BizException;

import java.util.Collection;

/**
 * 自定义的精准分片（分库策略）
 * @author hsj
 * @date 2023/10/30 14:54
 */
public class CustomDBPreciseShardingAlgorithm implements PreciseShardingAlgorithm<String> {

    /**
     *
     * @param databaseNames 数据源集合在分库时值为所有分⽚库的集合 databaseNames
     * @param preciseShardingValue  分⽚属性，包括logicTableName 为逻辑表，
     *                              columnName 分⽚健
     *                              value 为从 SQL 中解析出的分⽚健的值
     * @return
     */
    @Override
    public String doSharding(Collection<String> databaseNames, PreciseShardingValue<String> preciseShardingValue) {


        /**获取短链码的第一位 即库位*/
        String codePrefix = preciseShardingValue.getValue().substring(0,1);
        for (String database : databaseNames) {
            /**获取库名的最后一位*/
            String suffix = database.substring(database.length() - 1);
             /**如果一致则返回*/
            if (codePrefix.equals(suffix)){
                return database;
            }

        }

        throw new BizException(BizCodeEnum.DB_ROUTE_NOT_FOUND);
    }

}
